﻿using UnityEngine;
using System.Collections;

public class Missile : MonoBehaviour 
{
	private bool m_isActive;
	public float m_speed;
	private Vector3 m_direction;
	public Sprite m_frame1;
	public Sprite m_frame2;
	private SpriteRenderer m_spriteRenderer;
	private bool m_frameSwitcher;
	public Explode m_explosion;
	private int m_explosionCount = 0;
	private SceneManager m_sceneManager;
	// Use this for initialization
	void Start () 
	{
		m_isActive = false;
		m_spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
		m_sceneManager = GameObject.Find ("SceneManager").GetComponent<SceneManager> ();
		m_frameSwitcher = true;
		m_explosionCount = 0;
		///Destroy(gameObject, 2.0f);
	}

	void Awake()
	{
		m_explosionCount = 0;
	}
	// Update is called once per frame
	void Update () 
	{
		if( m_isActive )
		{
			m_frameSwitcher = !m_frameSwitcher;

			if( m_frameSwitcher )
				m_spriteRenderer.sprite = m_frame1;
			else
				m_spriteRenderer.sprite = m_frame2;
				
			transform.position += m_direction * m_speed * Time.deltaTime;
		}
	}
	
	public bool IsActive()
	{
		return m_isActive;
	}

	void Explode(Vector3 loc)
	{
		if( m_explosionCount >= 1 )
			return;

		m_isActive = false;
		Instantiate(m_explosion, loc, Quaternion.identity);
		transform.position = new Vector3(-1000.0f, -1000.0f, 0.0f);
		m_explosionCount += 1;
	}
	bool CheckBounds(Vector3 _position, float _limitX, float _limitY)
	{
		if( _position.x < 0 )
			return false;
		
		if( _position.x > _limitX )
			return false;
		
		if( _position.y < 0 )
			return false;
		
		if( _position.y  > _limitY )
			return false;

		return true; 
	}

	public void SetPosition(Vector3 _position)
	{
		transform.position = _position;
	}
	public void SetRotation(Quaternion _rotation)
	{
		transform.rotation = _rotation;
	}
	public void LaunchMissile()
	{
		m_isActive = true;
		m_explosionCount = 0;
	}
	public void SetDirection(Vector3 _direction)
	{
		m_direction = _direction;
	}

	void OnCollisionEnter2D(Collision2D coll) 
	{
		if( !m_isActive )
			return;

		Vector3 colPoint = coll.transform.position;// coll.gameObject.transform.position;
		colPoint.x += 16.0f;
		colPoint.y += 16.0f;
		Debug.Log("Missile Collided with " + coll.gameObject.tag);

		if (coll.gameObject.tag == "Brick") 
		{
			Debug.Log("......Destroying : " + coll.gameObject.name);
			coll.gameObject.SetActive( false );
			Destroy( coll.gameObject );
		}

		else if( coll.gameObject.tag == "TargetPickup" )
		{
			SceneInformation.GetInstance().m_playerScore += 1;
			//Hit by a Enemy, so destroy it
			m_sceneManager.RespawnFuelBarrel();
		}
		Explode(colPoint);
	}
}
